-- pgsql
-- Author: Colocasia
-- Date: 2018-03-14

local skynet = require "skynet";
require "skynet.manager";
local pgsql = require "us.db.pgsql";
local log = require "log";

local SEND_SESSION_NO_RET = 0

local us_pgsql = {};
local db_pool = {};

local maxconnect = nil;
local index = 1;

local function getconn()
    local db = db_pool[index];
    index = index + 1;
    if index > maxconnect then
        index = 1;
    end
    return db;
end

-- execute sql
function us_pgsql.execute(sql)
    local db = getconn();
    assert(db);
    print("us_pgsql query->", sql)
    return db:query(sql);
end

-- start service
function us_pgsql.start()
    maxconnect = 10;
    -- print("us_pgsql.start")
    for i=1, maxconnect do
        local conf = {
            host = "127.0.0.1",
            port = 5432,
            user = "aliner",
            database = "us_db",
            password = "180506",
        }
        local db = pgsql.connect(conf)
        if db then
            table.insert(db_pool, db);
        else
            log.error("pgsql connect error");
        end
    end
    return true;
end

function on_cmd_err(err)
    log.error("pgsql execute cmd error: %s", err);
end

function us_pgsql.init()
    skynet.dispatch("lua", function(session, source, cmd, ...)
        local f = assert(us_pgsql[cmd], "us_pgsql cmd=>"..cmd.." not found");
        local function ret(ok, ...)
            if session ~= SEND_SESSION_NO_RET then
                skynet.retpack (...)
            end
        end
        ret(xpcall(f, on_cmd_err, ...));
    end)
    skynet.register(SERVICE_NAME);
end

skynet.start(us_pgsql.init);

